package com.example.servlet;

import com.example.bean.Student;
import com.example.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 学生信息管理Servlet
 * 使用JSP + Servlet + JavaBean架构
 * Servlet作为控制器，调用Service层（JavaBean）处理业务逻辑
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    // 使用Service层（JavaBean）而不是直接使用DAO
    private StudentService studentService = new StudentService();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");
        if (action == null) {
            action = "list";
        }

        switch (action) {
            case "list":
                listStudents(request, response);
                break;
            case "detail":
                showDetail(request, response);
                break;
            case "add":
                showAddForm(request, response);
                break;
            case "edit":
                showEditForm(request, response);
                break;
            case "delete":
                deleteStudent(request, response);
                break;
            default:
                listStudents(request, response);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");

        if ("save".equals(action)) {
            saveStudent(request, response);
        } else if ("update".equals(action)) {
            updateStudent(request, response);
        }
    }

    /**
     * 显示学生列表
     */
    private void listStudents(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 调用Service层（JavaBean）获取数据
        List<Student> students = studentService.getAllStudents();
        request.setAttribute("students", students);
        request.getRequestDispatcher("/studentList.jsp").forward(request, response);
    }

    /**
     * 显示学生详情
     */
    private void showDetail(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        // 调用Service层（JavaBean）获取数据
        Student student = studentService.getStudentById(id);
        request.setAttribute("student", student);
        request.getRequestDispatcher("/studentDetail.jsp").forward(request, response);
    }

    /**
     * 显示添加表单
     */
    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/studentForm.jsp").forward(request, response);
    }

    /**
     * 显示编辑表单
     */
    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        // 调用Service层（JavaBean）获取数据
        Student student = studentService.getStudentById(id);
        request.setAttribute("student", student);
        request.getRequestDispatcher("/studentForm.jsp").forward(request, response);
    }

    /**
     * 保存新学生
     */
    private void saveStudent(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            Student student = new Student();
            student.setpId(request.getParameter("pId"));
            student.setNo(request.getParameter("no"));
            student.setName(request.getParameter("name"));
            student.setSex(request.getParameter("sex"));

            String birthdateStr = request.getParameter("birthdate");
            if (birthdateStr != null && !birthdateStr.isEmpty()) {
                Date birthdate = dateFormat.parse(birthdateStr);
                student.setBirthdate(birthdate);
            }

            // 调用Service层（JavaBean）处理业务逻辑
            boolean success = studentService.addStudent(student);
            if (success) {
                response.sendRedirect(request.getContextPath() + "/student?action=list");
            } else {
                request.setAttribute("error", "添加学生失败！");
                request.getRequestDispatcher("/studentForm.jsp").forward(request, response);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("error", "日期格式错误！");
            request.getRequestDispatcher("/studentForm.jsp").forward(request, response);
        }
    }

    /**
     * 更新学生信息
     */
    private void updateStudent(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            Student student = new Student();
            student.setId(Integer.parseInt(request.getParameter("id")));
            student.setpId(request.getParameter("pId"));
            student.setNo(request.getParameter("no"));
            student.setName(request.getParameter("name"));
            student.setSex(request.getParameter("sex"));

            String birthdateStr = request.getParameter("birthdate");
            if (birthdateStr != null && !birthdateStr.isEmpty()) {
                Date birthdate = dateFormat.parse(birthdateStr);
                student.setBirthdate(birthdate);
            }

            // 调用Service层（JavaBean）处理业务逻辑
            boolean success = studentService.updateStudent(student);
            if (success) {
                response.sendRedirect(request.getContextPath() + "/student?action=list");
            } else {
                request.setAttribute("error", "更新学生信息失败！");
                request.setAttribute("student", student);
                request.getRequestDispatcher("/studentForm.jsp").forward(request, response);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("error", "日期格式错误！");
            request.getRequestDispatcher("/studentForm.jsp").forward(request, response);
        }
    }

    /**
     * 删除学生
     */
    private void deleteStudent(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        // 调用Service层（JavaBean）处理业务逻辑
        studentService.deleteStudent(id);
        response.sendRedirect(request.getContextPath() + "/student?action=list");
    }
}

